package org.jeecg.modules.wei.job;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.Reader;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.HttpRequest;
import org.jeecg.modules.wei.entity.WeiArticle;
import org.jeecg.modules.wei.entity.WeiComment;
import org.jeecg.modules.wei.service.IWeiArticleService;
import org.jeecg.modules.wei.service.IWeiCommentService;
import org.jeecg.modules.wei.util.WeiboUtils;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;

import lombok.extern.slf4j.Slf4j;

/**
 * 微博   文章列表、评论列表
 * @author Scott
 */
@Slf4j
public class WeiboCommentJob implements Job {
	
	@Autowired
	private IWeiArticleService weiArticleService;
	
	@Autowired
	private IWeiCommentService weiCommentService;
	/**
	 * 若参数变量名修改 QuartzJobController中也需对应修改
	 */
	private String parameter;

	public void setParameter(String parameter) {
		this.parameter = parameter;
	}
	
	@Override
	public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
		log.info(" 微博评论 定时器 !" );

		String accessToken = get_token();
		int pages = Integer.parseInt(parameter);
		
		for(int i = 1; i <= pages; i++) {
			JSONObject json = other(accessToken, i);
			if(json != null) {
				JSONArray commentlist = json.getJSONArray("comments");
				 if(commentlist != null && commentlist.size() > 0) {
					 for (int j = 0; j < commentlist.size(); j++) {
							JSONObject  comment = commentlist.getJSONObject(j);
							System.out.println(comment.getString("text"));
							System.out.println(comment.getString("id"));
							System.out.println(comment.getString("created_at"));
							WeiComment info = new WeiComment();
							info.setId(comment.getString("id"));
							JSONObject status = comment.getJSONObject("status");
							info.setMsgid(status.getString("id"));
							info.setContent(comment.getString("text"));
							JSONObject user = comment.getJSONObject("user");
							//{"is_teenager":0,"allow_all_act_msg":false,"favourites_count":0,"urank":3,"verified_trade":"","weihao":"","verified_source_url":"","type":1,"province":"13","screen_name":"客户_20927","id":5883186267,"geo_enabled":true,"like_me":false,"like":false,"level":1,"verified_type":-1,"user_limit":0,"tab_manage":"[0, 0]","extend":{"mbprivilege":"0000000000000000000000000000000000000000000000000000000000000000","privacy":{"mobile":1}},"badge":{"panda":0,"relation_display":0,"yiqijuan_2018":0,"status_visible":0,"bind_taobao":0,"kpl_2018":0,"asiad_2018":0,"follow_whitelist_video":0,"lol_msi_2017":0,"lol_gm_2017":0,"denglong_2019":0,"ali_1688":0,"unread_pool":0,"qixi_2018":0,"super_star_2017":0,"vip_activity2":0,"super_star_2018":0,"vip_activity1":0,"weibo_display_fans":0,"dailv_2018":0,"meilizhongguo_2018":0,"hongbaofei_2019":0,"uc_domain":0,"league_badge_2018":0,"unread_pool_ext":0,"memorial_2018":0,"self_media":0,"wusi_2019":0,"dailv":0,"hongrenjie_2019":0,"uve_icon":0,"cz_wed_2017":0,"double11_2018":0,"wbzy_2018":0,"zongyiji":0,"lol_s8":0,"enterprise":0,"user_name_certificate":1,"national_day_2018":0,"fools_day_2016":0,"womensday_2018":0,"suishoupai_2019":0,"suishoupai_2018":0,"taobao":0,"dzwbqlx_2016":0,"discount_2016":0,"wenda":0,"gongyi_level":0,"fu_2019":0,"gongyi":0,"worldcup_2018":0,"league_badge":0,"travel_2017":0,"uefa_euro_2016":0,"video_attention":0,"inspector":0,"v_influence_2018":0,"avengers_2019":0,"earth_2019":0,"wenchuan_10th":0,"daiyan":0,"wenda_v2":0,"anniversary":0},"pagefriends_count":0,"domain":"","following":false,"name":"客户_20927","idstr":"5883186267","follow_me":false,"friends_count":62,"credit_score":80,"gender":"f","city":"4","profile_url":"u/5883186267","description":"","created_at":"Thu Mar 17 10:29:08 +0800 2016","remark":"","ptype":0,"badge_top":"","verified_reason_url":"","block_word":0,"avatar_hd":"http://tvax4.sinaimg.cn/default/images/default_avatar_female_180.gif","mbtype":0,"bi_followers_count":0,"user_ability":0,"is_teenager_list":0,"verified_reason":"","story_read_state":-1,"video_status_count":0,"mbrank":0,"lang":"zh-cn","class":1,"has_ability_tag":0,"star":0,"allow_all_comment":true,"online_status":0,"ulevel":0,"verified":false,"profile_image_url":"http://tvax4.sinaimg.cn/default/images/default_avatar_female_50.gif","block_app":0,"url":"","avatar_large":"http://tvax4.sinaimg.cn/default/images/default_avatar_female_180.gif","statuses_count":0,"vclub_member":0,"followers_count":0,"is_guardian":0,"location":"河北 邯郸","insecurity":{"sexual_content":false},"verified_source":""}
							if(user != null) {
								info.setNickname(user.getString("screen_name"));
								info.setHeadimgurl(user.getString("avatar_hd"));
								info.setOpenid(user.getString("id"));
							}else {
								System.out.println("暂无头像");
							}
							
							info.setType(2);
							info.setCreateTime(DateUtils.stringToGMT(comment.getString("created_at")));
							try {
								weiCommentService.saveOrUpdate(info);
							} catch (Exception e) {
								e.printStackTrace();
							}
						
							System.out.println("-----------------------------------------------------------");
						}
				 }
				
				
				
			}
			
			
		}
		
	}
	
	
	
	public String get_token() {
		String result = HttpRequest.sendGet("http://gongan.hbweiyinqing.cn/f/dataapp/api/get_access_token", "");
		System.out.println("获取token"+result);
		JSONObject json = JSONObject.parseObject(result);
		if(json.getString("code").equals("200")) {
			return json.getString("token");
		}else {
			return  null;
		}
	}
	
	public JSONObject other(String accessToken,int page) {
		String result = HttpRequest.sendGet("https://c.api.weibo.com/2/comments/to_me/other.json", "access_token="+accessToken+"&uid=1808545011&page="+page);
		System.out.println("获取token"+result);
		return JSONObject.parseObject(result);
	}
	
	public  void getcommentlist(String accessToken,String msgid) {
		JSONObject json = commentlist(accessToken, msgid);

		if(json != null) {
			 JSONArray commentlist = json.getJSONArray("comments");
			 if(commentlist != null && commentlist.size() > 0) {
				 for (int j = 0; j < commentlist.size(); j++) {
						JSONObject  comment = commentlist.getJSONObject(j);
						System.out.println(comment.getString("text"));
						System.out.println(comment.getString("id"));
						System.out.println(comment.getString("created_at"));
						WeiComment info = new WeiComment();
						info.setId(comment.getString("id"));
						info.setMsgid(msgid);
						info.setContent(comment.getString("text"));
						JSONObject user = comment.getJSONObject("user");
						//{"is_teenager":0,"allow_all_act_msg":false,"favourites_count":0,"urank":3,"verified_trade":"","weihao":"","verified_source_url":"","type":1,"province":"13","screen_name":"客户_20927","id":5883186267,"geo_enabled":true,"like_me":false,"like":false,"level":1,"verified_type":-1,"user_limit":0,"tab_manage":"[0, 0]","extend":{"mbprivilege":"0000000000000000000000000000000000000000000000000000000000000000","privacy":{"mobile":1}},"badge":{"panda":0,"relation_display":0,"yiqijuan_2018":0,"status_visible":0,"bind_taobao":0,"kpl_2018":0,"asiad_2018":0,"follow_whitelist_video":0,"lol_msi_2017":0,"lol_gm_2017":0,"denglong_2019":0,"ali_1688":0,"unread_pool":0,"qixi_2018":0,"super_star_2017":0,"vip_activity2":0,"super_star_2018":0,"vip_activity1":0,"weibo_display_fans":0,"dailv_2018":0,"meilizhongguo_2018":0,"hongbaofei_2019":0,"uc_domain":0,"league_badge_2018":0,"unread_pool_ext":0,"memorial_2018":0,"self_media":0,"wusi_2019":0,"dailv":0,"hongrenjie_2019":0,"uve_icon":0,"cz_wed_2017":0,"double11_2018":0,"wbzy_2018":0,"zongyiji":0,"lol_s8":0,"enterprise":0,"user_name_certificate":1,"national_day_2018":0,"fools_day_2016":0,"womensday_2018":0,"suishoupai_2019":0,"suishoupai_2018":0,"taobao":0,"dzwbqlx_2016":0,"discount_2016":0,"wenda":0,"gongyi_level":0,"fu_2019":0,"gongyi":0,"worldcup_2018":0,"league_badge":0,"travel_2017":0,"uefa_euro_2016":0,"video_attention":0,"inspector":0,"v_influence_2018":0,"avengers_2019":0,"earth_2019":0,"wenchuan_10th":0,"daiyan":0,"wenda_v2":0,"anniversary":0},"pagefriends_count":0,"domain":"","following":false,"name":"客户_20927","idstr":"5883186267","follow_me":false,"friends_count":62,"credit_score":80,"gender":"f","city":"4","profile_url":"u/5883186267","description":"","created_at":"Thu Mar 17 10:29:08 +0800 2016","remark":"","ptype":0,"badge_top":"","verified_reason_url":"","block_word":0,"avatar_hd":"http://tvax4.sinaimg.cn/default/images/default_avatar_female_180.gif","mbtype":0,"bi_followers_count":0,"user_ability":0,"is_teenager_list":0,"verified_reason":"","story_read_state":-1,"video_status_count":0,"mbrank":0,"lang":"zh-cn","class":1,"has_ability_tag":0,"star":0,"allow_all_comment":true,"online_status":0,"ulevel":0,"verified":false,"profile_image_url":"http://tvax4.sinaimg.cn/default/images/default_avatar_female_50.gif","block_app":0,"url":"","avatar_large":"http://tvax4.sinaimg.cn/default/images/default_avatar_female_180.gif","statuses_count":0,"vclub_member":0,"followers_count":0,"is_guardian":0,"location":"河北 邯郸","insecurity":{"sexual_content":false},"verified_source":""}
						if(user != null) {
							info.setNickname(user.getString("screen_name"));
							info.setHeadimgurl(user.getString("avatar_hd"));
							info.setOpenid(user.getString("id"));
						}else {
							System.out.println("暂无头像");
						}
						
						info.setType(2);
						info.setCreateTime(DateUtils.stringToGMT(comment.getString("created_at")));
						try {
							weiCommentService.saveOrUpdate(info);
						} catch (Exception e) {
							e.printStackTrace();
						}
					
						System.out.println("-----------------------------------------------------------");
					}
			 }
		}
	}
	
	
	
	
	
	/**
	 * 批量获取用户个人微博列表。
	 * @param accessToken
	 * @param day
	 * @return
	 */
	public JSONObject commentlist(String accessToken,String msgid) {
		String result = HttpRequest.sendGet("https://c.api.weibo.com/2/comments/show/all.json", "access_token=2.00NeCenHXIQtsBdb00039e90d2myHD&id="+msgid);
		System.out.println("获取token"+result);
		return JSONObject.parseObject(result);
	}
	
	
	private static String readAll(Reader rd) throws IOException {
		StringBuilder sb = new StringBuilder();
		int cp;
		while ((cp = rd.read()) != -1) {
			sb.append((char) cp);
		}
		return sb.toString();
	}

	public static JSONObject postRequestFromUrl(String url, String body) throws IOException, JSONException {
		URL realUrl = new URL(url);
		URLConnection conn = realUrl.openConnection();
		conn.setDoOutput(true);
		conn.setDoInput(true);
		PrintWriter out = new PrintWriter(conn.getOutputStream());
		out.print(body);
		out.flush();

		InputStream instream = conn.getInputStream();
		try {
			BufferedReader rd = new BufferedReader(new InputStreamReader(instream, Charset.forName("UTF-8")));
			String jsonText = readAll(rd);
			JSONObject json = JSONObject.parseObject(jsonText);
			return json;
		} finally {
			instream.close();
		}
	}

	public static JSONObject getRequestFromUrl(String url) throws IOException, JSONException {
		URL realUrl = new URL(url);
		URLConnection conn = realUrl.openConnection();
		InputStream instream = conn.getInputStream();
		try {
			BufferedReader rd = new BufferedReader(new InputStreamReader(instream, Charset.forName("UTF-8")));
			String jsonText = readAll(rd);
			JSONObject json = JSONObject.parseObject(jsonText);
			return json;
		} finally {
			instream.close();
		}
	}
	
	public static void main(String[] args) {
		
	}
	
}
